import logging
from typing import Optional

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

maintain_level_router = APIRouter(prefix="/maintain/maintainLevel", tags=["保养级别管理"],
                                  dependencies=[Depends(oauth2_scheme)])


class MaintainLevelSearch(PaginationBase):
    fmmlevelname: str = Field("", description="保养级别名")


@maintain_level_router.get("/list", summary="保养级别查询接口")
def list_maintain_level(search: MaintainLevelSearch, db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from s_ts_maintain_level where 1=1"
    if search.fmmlevelname != "":
        sql = sql + " and fmmlevelname like concat('%', :fmmlevelname ,'%')"
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fmmlevelno,fmmlevelname,fmemo,fupddate,foperator"
    sql = sql + " from s_ts_maintain_level where 1=1"
    if search.fmmlevelname != "":
        sql = sql + " and fmmlevelname like concat('%', :fmmlevelname ,'%')"
    if search.order == "desc":
        sql = sql + " order by  fmmlevelno desc "
    else:
        sql = sql + " order by  fmmlevelno "
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fmmlevelno'] = data[key][0]
        d1['fmmlevelname'] = data[key][1]
        d1['fmemo'] = data[key][2]
        d1['fupddate'] = data[key][3]
        d1['foperator'] = data[key][4]
        data_list.append(d1)

    info_dict = {"list": data_list, "limit": search.limit,
                 "page": search.pageIndex, "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class MaintainLevelCreate(BaseModel):
    """保养级别新增请求参数"""
    fmmlevelno: str = Field(..., description="保养级别编号（唯一标识）")
    fmmlevelname: str = Field(..., description="保养级别名称")
    foperator: str = Field(..., description="操作人")
    fupddate: str = Field(..., description="更新日期(yyyy-MM-dd HH:mm:ss)")
    fmemo: Optional[str] = Field("", description="备注")


@maintain_level_router.post("/create", summary="保养级别新增接口")
def create_maintain_level(create: MaintainLevelCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select fmmlevelno from s_ts_maintain_level where fmmlevelno= :fmmlevelno "
            data = db.execute(text(sql), {"fmmlevelno": create.fmmlevelno}).fetchall()

            if len(data) > 0:
                return BaseResponse.error(message="编号已存在")
            else:
                sql = "insert into s_ts_maintain_level(fmmlevelno,fmmlevelname,fmemo,fupddate,foperator)"
                sql = sql + " values( :fmmlevelno , :fmmlevelname , :fmemo , :fupddate , :foperator );"
                db.execute(text(sql), {
                    "fmmlevelno": create.fmmlevelno,
                    "fmmlevelname": create.fmmlevelname,
                    "fmemo": create.fmemo,
                    "fupddate": create.fupddate,
                    "foperator": create.foperator
                })

                # 返回
                d1 = {}
                d1["fmmlevelno"] = create.fmmlevelno
                d1["fmmlevelname"] = create.fmmlevelname
                d1["fmemo"] = create.fmemo
                d1["fupddate"] = create.fupddate
                d1["foperator"] = create.foperator
                return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@maintain_level_router.post("/update", summary="保养级别改接口")
def update_maintain_level(update: MaintainLevelCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "update s_ts_maintain_level"
            sql = sql + " set fmmlevelname= :fmmlevelname ,fmemo= :fmemo "
            sql = sql + ",fupddate= :fupddate ,foperator= :foperator "
            sql = sql + " where fmmlevelno= :fmmlevelno "
            db.execute(text(sql), {
                "fmmlevelname": update.fmmlevelname,
                "fmemo": update.fmemo,
                "fupddate": update.fupddate,
                "foperator": update.foperator,
                "fmmlevelno": update.fmmlevelno
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@maintain_level_router.post("/delete/{fmmlevelno}", summary="保养级别删除接口")
def delete_maintain_level(fmmlevelno: str = Path(description="保养级别编号"), db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select count(1) from lims.s_tc_mm_head where fmmlevelno= :fmmlevelno "
            data = db.execute(text(sql), {"fmmlevelno": fmmlevelno}).fetchall()
            if data[0][0] > 0:
                return BaseResponse.error(message="该资料在使用，不能删除")
            else:
                sql = "delete from s_ts_maintain_level where fmmlevelno= :fmmlevelno "
                db.execute(text(sql), {"fmmlevelno": fmmlevelno})
                return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
